package satir.command;

import java.util.ArrayList;
import java.util.Scanner;

import satir.card.Choice;
import satir.card.Question;
import satir.framework.InputValidator;
import satir.player.Player;

/**
 * The Class AskQuestionCmd.
 * @version 3.0 April 2012
 * @author Creative Family
 */
public class AskQuestionCmd implements Command {

    /** The question. */
    private Question question;

    /** The player. */
    private Player player;

    /** The user answer. */
    private Choice userAnswer;

    /**
     * Instantiates a new ask question command.
     * @param question
     *            the question
     * @param player
     *            the player
     */
    public AskQuestionCmd(final Question question, final Player player) {
	this.question = question;
	this.player = player;
    }

    /**
     *  Execute the command action.
     */
    @Override
    public void execute() {
	System.out.println(question.getQuestion());
	ArrayList<Choice> choices = question.getChoices();
	for (int i = 0; i < choices.size(); i++) {
	    System.out.println((i + 1) + ". " + choices.get(i).getContent());
	}
	Scanner sc = new Scanner(System.in);
	System.out.println("Your Answer?");

	boolean isInvalid = true;
	int ansIndex = 0;
	do {
	    String input = sc.next();
	    isInvalid = !InputValidator.isInteger(input);
	    if (isInvalid) {
		System.out.println("It is not a number.");
		askQuestion(choices);
	    } else {
		ansIndex = Integer.parseInt(input);
		isInvalid = !InputValidator.isWithinRange(ansIndex, 1, choices.size());
		if (isInvalid) {
		    System.out.println("Out of range!");
		    askQuestion(choices);
		}
	    }
	} while (isInvalid);

	userAnswer = choices.get(ansIndex - 1);
	player.increaseSelfEsteem(userAnswer.getRewardSE());
	System.out.println(userAnswer.getRewardSE() + " Awarded!!");
    }

    /**
     * Ask question.
     * @param choices the choices
     */
    protected void askQuestion(final ArrayList<Choice> choices) {
	System.out.print("Please indicate your selection: ");
	for (int i = 0; i < choices.size(); i++) {
	    if (i != 0) {
		System.out.print(",");
	    }
	    System.out.println(" [" + (i + 1) + "] "
		    + choices.get(i).getContent());
	}
	System.out.print("\n");
    }

    /**
     * Gets the choice.
     * @return the choice
     */
    public Choice getChoice() {
	return userAnswer;
    }

    /**
     * Gets the player.
     * @return the player
     */
    public Player getPlayer() {
	return player;
    }

}
